import { Form, Input, Modal, Spin } from 'antd';

import React, { useEffect, useState } from 'react';
import type { AuthPermission, AuthPermissionEditItem } from '../data';

interface AuthPermissionEditFormProps {
  // 规则的唯一id
  ruleId: string;
  // 请求修改数据的回调
  onSubmit: (values: AuthPermissionEditItem) => void;
  // 取消窗口的回调
  onCancel: (flag?: boolean) => void;
  // 窗口是否可见
  modalVisible: boolean;
  // 获取规则详情的请求
  request: (sysDict: string) => Promise<{ success: boolean; data: AuthPermission | null }>;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 4 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 20 },
    sm: { span: 20 },
  },
};

const AuthPermissionEditForm: React.FC<AuthPermissionEditFormProps> = (props) => {
  const [form] = Form.useForm();
  const [loadingRequest, setLoadingRequest] = useState<boolean>(false);
  const [sysDict, setSysDict] = useState<AuthPermissionEditItem>({
    id: '',
    name: '',
    code: '',
  });

  const {
    ruleId,
    onSubmit: handleEdit,
    onCancel: handleEditModalVisible,
    modalVisible: editModalVisible,
  } = props;

  useEffect(() => {
    if (!ruleId) throw new Error('ruleId 不能为空');
    setLoadingRequest(true);

    props
      .request(ruleId)
      .then((res) => {
        if (res.success && res.data !== null) {
          form.setFieldsValue(res.data);
        }
      })
      .finally(() => {
        setLoadingRequest(false);
      });
  }, ['ruleId']);

  const onModalOk = async () => {
    const fieldsValue = await form.validateFields();
    const dictItem: AuthPermission = { ...fieldsValue, ...sysDict, id: ruleId };
    handleEdit(dictItem);
  };

  return (
    <Modal
      title="修改账号权限字典"
      visible={editModalVisible}
      destroyOnClose
      width={700}
      onOk={() => onModalOk()}
      onCancel={() => handleEditModalVisible(false)}
      afterClose={() => handleEditModalVisible()}
      okText="确定"
      cancelText="取消"
    >
      <Spin spinning={loadingRequest}>
        <Form {...formItemLayout} form={form}>
          <Form.Item
            name="accessCode"
            label="权限识别码"
            rules={[{ required: false, message: '必填' }]}
          >
            <Input disabled />
          </Form.Item>

          <Form.Item name="name" label="权限名称" rules={[{ required: true, message: '选填' }]}>
            <Input onChange={(value) => setSysDict({ ...sysDict, name: value.target.value })} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
};
export default AuthPermissionEditForm;
